package com.wdh.kjs.activity;

import android.app.AlertDialog;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.Handler;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.google.gson.Gson;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest;
import com.wdh.kjs.MainActivity;
import com.wdh.kjs.R;
import com.wdh.kjs.http.Httpurl;
import com.wdh.kjs.http.response.MyCookieStore;
import com.wdh.kjs.model.JsonModel;
import com.wdh.kjs.model.JsonModel_my;
import com.wdh.kjs.util.PhonenumUtil;
import com.wdh.kjs.util.ToastUtils;

import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONObject;

/**
 * Created by feifei on 2016/4/21.
 */
public class FaRenBangdingActivity extends BaseTopActivity implements View.OnClickListener{
    private EditText bangding_phone;
    private Button bangding_confirm;
    private JsonModel_my jsonModel_my;
    private Button bangding_getmsg;
    private TimeCount time;
    private JsonModel jsonModel;
    private String zhanghu;
    private EditText bangding_code;
    private String mima;
    private String farenphone;
    private String farenname;
    private LinearLayout ii_farenshouji;
    private String partId;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.bangding);

        SharedPreferences sharedPreferences = getSharedPreferences("logininfo", MODE_PRIVATE);
        zhanghu = sharedPreferences.getString("zhanghao", "");
        mima = sharedPreferences.getString("mima", "");
//        farenphone = sharedPreferences.getString("faren", "");
//        farenname= sharedPreferences.getString("farenname", "");
        partId = sharedPreferences.getString("loginToken", "");
        initview();
        bangding_confirm.setText("点击验证");
        ii_farenshouji.setVisibility(View.GONE);
        denglu();
        time = new TimeCount(60000, 1000);
    }

    private void denglu() {
        RequestParams params = new RequestParams();
        params.addBodyParameter("USERNAME", zhanghu);
        params.addBodyParameter("PASSWORD", mima);
        final HttpUtils http = new HttpUtils();
        http.send(HttpRequest.HttpMethod.POST, Httpurl.URL_LOGIN, params, new RequestCallBack<String>() {

            @Override
            public void onSuccess(ResponseInfo<String> responseInfo) {
                
                Gson gson = new Gson();
                jsonModel = gson.fromJson(responseInfo.result, JsonModel.class);
                String m = jsonModel.getPartyId();

                if (jsonModel._LOGIN_PASSED_()) {
                    DefaultHttpClient zpf = (DefaultHttpClient) http.getHttpClient();
                    MyCookieStore.secondCookieStore = zpf.getCookieStore();
                    SharedPreferences.Editor editor = getSharedPreferences("logininfo", MODE_PRIVATE).edit();
                    editor.putString("loginToken", jsonModel.getPartyId());
                    editor.putString("nickName", jsonModel.getNickName());
                    editor.putString("farenphone", jsonModel.getoRepresentPhone());
                    editor.putString("phoneNumber", jsonModel.getPhoneNumber());

                    editor.putString("farenname", jsonModel.getoRepresentName());
                    editor.putString("levels",jsonModel.getLevels());
                    editor.putString("type",jsonModel.getType());
                    editor.putString("zhanghao",zhanghu);
                    editor.putString("mima",mima);
                    editor.commit();
                }


            }

            @Override
            public void onFailure(HttpException error, String msg) {


            }
        });

    }

    private void initview() {
        initTopBar("法人手机验证");
        bangding_code = (EditText) findViewById(R.id.bangding_code);
        bangding_phone = (EditText)findViewById(R.id.bangding_phone);
        bangding_confirm = (Button)findViewById(R.id.bangding_confirm);
        bangding_getmsg = (Button) findViewById(R.id.bangding_getmsg);
        ii_farenshouji = (LinearLayout) findViewById(R.id.ii_farenshouji);
        bangding_confirm.setOnClickListener(this);
        bangding_getmsg.setOnClickListener(this);
    }

    private void loadData() {

        RequestParams params = new RequestParams();

        params.addBodyParameter("verificationCode", bangding_code.getText().toString());
        params.addBodyParameter("partyId", partId);
        HttpUtils http = new HttpUtils();
        http.configCookieStore(MyCookieStore.secondCookieStore);
        http.send(HttpRequest.HttpMethod.POST, Httpurl.URL_FAREN_TEL, params, new RequestCallBack<String>() {

            @Override
            public void onSuccess(ResponseInfo<String> responseInfo) {
                Gson gson = new Gson();
                jsonModel_my = gson.fromJson(responseInfo.result, JsonModel_my.class);


                if (jsonModel_my.getMessageAccept().equals("success")) {
                    trueDialogShow("手机验证成功！");
                    new Handler().postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            Intent intent = new Intent();
                            finish();
                            intent.setClass(FaRenBangdingActivity.this, MainActivity.class);
                            intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                            startActivity(intent);
                        }
                    }, 2000);
                } else {
                    falseDialogShow("手机验证失败！");
                }
            }

            @Override
            public void onFailure(HttpException error, String msg) {
                ToastUtils.showShort(getApplicationContext(), "网络异常！");
            }
        });
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()){
            case R.id.bangding_confirm:

                if(bangding_code.getText().toString().equals("")){
                    falseDialogShow("请输入验证码！");
                }else {
                    loadData();
                }
                break;
            case R.id.bangding_getmsg: {
                SharedPreferences mysharedPreferences = getSharedPreferences("logininfo", MODE_PRIVATE);
                farenphone= mysharedPreferences.getString("farenphone", "");
                farenname= mysharedPreferences.getString("farenname", "");
                    time.start();
                    intcode();

                break;
            }
            default:
                break;
        }
    }

    private void intcode() {

        RequestParams params = new RequestParams();
        params.addBodyParameter("phoneNumber", farenphone);
        params.addBodyParameter("sendName", farenname);
        final HttpUtils http = new HttpUtils();
        http.send(HttpRequest.HttpMethod.POST, Httpurl.URL_FAREN_Phone, params, new RequestCallBack<String>() {

            @Override
            public void onSuccess(ResponseInfo<String> responseInfo) {


                Gson gson = new Gson();
                jsonModel = gson.fromJson(responseInfo.result, JsonModel.class);
//                    if (jsonModel.success) {
                DefaultHttpClient zpf = (DefaultHttpClient) http.getHttpClient();
                MyCookieStore.secondCookieStore = zpf.getCookieStore();

//                    }


            }

            @Override
            public void onFailure(HttpException error, String msg) {

                ToastUtils.showShort(FaRenBangdingActivity.this, "网络异常！");
            }
        });


    }

    private void falseDialogShow(String hint) {
        View dialog = getLayoutInflater().inflate(R.layout.view_dialog_false, null);
        Button bt_dialog_false_negative = (Button) dialog.findViewById(R.id.bt_dialog_false_negative);
        Button bt_dialog_false_positive = (Button) dialog.findViewById(R.id.bt_dialog_false_positive);
        TextView tv_dialog_false_hint = (TextView) dialog.findViewById(R.id.tv_dialog_false_hint);
        tv_dialog_false_hint.setText(hint);
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setView(dialog);
        builder.create();
        final AlertDialog dialogShow = builder.show();
        bt_dialog_false_negative.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                dialogShow.dismiss();
            }
        });
        bt_dialog_false_positive.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                dialogShow.dismiss();
                bangding_phone.setText("");
            }
        });
    }

    private void trueDialogShow(String hint) {
        View dialog = (LinearLayout) getLayoutInflater().inflate(R.layout.view_dialog_true, null);
        TextView tv_dialog_false_hint = (TextView) dialog.findViewById(R.id.tv_dialog_true_hint);
        tv_dialog_false_hint.setText(hint);
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setView(dialog);
        builder.create();
        final AlertDialog dialogShow = builder.show();

    }
    class TimeCount extends CountDownTimer {
        public TimeCount(long millisInFuture, long countDownInterval) {
            super(millisInFuture, countDownInterval);
        }

        @Override
        public void onFinish() {// 计时完毕
            bangding_getmsg.setText("发送验证码");
            bangding_getmsg.setClickable(true);
        }

        @Override
        public void onTick(long millisUntilFinished) {// 计时过程
            bangding_getmsg.setClickable(false);//防止重复点击
            bangding_getmsg.setText(millisUntilFinished / 1000 + "s后可重新获取");
        }
    }
}
